<?php
/**
 * @Author 张超.
 * @Copyright http://www.zhangchao.name
 * @Email 416716328@qq.com
 * @DateTime 2018/5/8 16:06
 * @Desc
 */

namespace app\common\controller;

use app\run\model\Admin;
use app\run\model\AuthGroup;
use app\run\model\AuthGroupAccess;
use app\run\model\MenusRule;
use \Auth;
use think\Controller;
use think\Db;
use think\facade\Config;
use think\facade\Session;

class Run extends Controller
{
    protected $userInfo;

    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        //读取缓存文件、并赋值
        $this->assign(['dev' => read_cache("develop")]);
        //权限检测、当前项目的权限、可选择显示、可不显示、但提示没有权限
        $auth = new Auth\Auth($this->request);
        //定义不需要权限访问的地址
        $noAuth = Config::get("auth.NOT_ALLOW_AUTH");
        //获取当前请求的路径地址
        $strAuth = $this->request->controller() . "/" . $this->request->action();
        //检查是否登录
        if (!$this->check_login()) {
            //若没有登录、则使用ip、自动创建一个用户
            $post['password'] = password_hash("123456", PASSWORD_BCRYPT);
            $post['exp_time'] = date("Y-m-d H:i:s");
            $post['name'] = $this->request->ip();
            //判断当前ip是否注册过
            $admin = new Admin();
            $isRegister = $admin->where('name', 'eq', $post['name'])->find();
            if ($isRegister) {
                //密码正确之后、将密码进行存储、存储方式为 转json之后base64、然后加上一个随机6位的数字
                Session::set(Config::get("auth.DEFAULT_LOGIN_SESSION"), base64_encode(json_encode($isRegister) . rand(100000, 999999)));
                Session::set("is_login", true);
                return $this->redirect(url("Index/index"));
            }
            $post['day_number'] = read_cache("develop", "day_number");//读取设置的每日限额
            $post['type'] = 2;
            $result = $admin->allowField(true)->save($post);
            //插入权限关联
            $AuthGroupAccess = new AuthGroupAccess();
            $post['uid'] = $admin->getLastInsID();
            $resultAccess = $AuthGroupAccess->allowField(true)->save(['uid' => $post['uid'], 'group_id' => 6]);
            $uInfo = $admin->where('id', 'eq', $post['uid'])->find();
            if ($result && $resultAccess) {
                Db::commit();
                //密码正确之后、将密码进行存储、存储方式为 转json之后base64、然后加上一个随机6位的数字
                Session::set(Config::get("auth.DEFAULT_LOGIN_SESSION"), base64_encode(json_encode($uInfo) . rand(100000, 999999)));
                Session::set("is_login", true);
                return $this->redirect(url("Index/index"));
            } else {
                Db::rollback();
                return $this->redirect(url("Login/index"));
            }
        } else {
            //如果已经登录
            $this->userInfo = json_decode(substr(base64_decode(session(Config::get("auth.DEFAULT_LOGIN_SESSION"))), 0, -6), true);
            $this->assign("user", $this->userInfo);
        }

//缓存当前访问路径、
session("thisurl", $strAuth);
//获取当前缓存中的路径
$this->assign("thisurl", session("thisurl"));
//输出当前访问的路径
$this->assign("befurl", $strAuth);
//如果有不需要权限控制的地址、则进行判断处理、以下代码位置不能变动
if (!empty($noAuth)) {
    if (in_array(strtolower($strAuth), $noAuth)) {
        return true;
    }
}
if (!$auth->check($strAuth, $this->userInfo['id'])) {
//            exit("<script src='/static/run/static/layui/layui.js'></script><script>layui.use(['layer','jquery'],function () {var layer = layui.layer,$ = layui.jquery;layer.msg('您缺少访问权限、3秒后自动关闭！',{icon:2},function() {layer.closeAll();var index = parent.layer.getFrameIndex(window.name);parent.layer.close(index);})})</script>");
    if ($this->request->isAjax()) {
        $this->ajaxRuturn(400, "您没有权限访问该操作！");
    }
}
}

public
function layAjax($code, $msg, $count, $data)
{
    // 返回JSON数据格式到客户端 包含状态信息
    header('Content-Type:application/json; charset=utf-8');
    $array['code'] = $code;
    $array['msg'] = $msg;
    $array['count'] = $count;
    $array['data'] = $data;
    exit(json_encode($array));
}

/**
 * @author by 张超 <Email:416716328@qq.com web:http://www.zhangchao.name>
 * @name 定义ajax请求返回的数据类型
 * @version 1.0.0
 * @funName ajaxRuturn
 * @param $code 状态码 200成功 400失败
 * @param $msg 返回的提示消息
 * @param $data 需要返回的数据
 * @return  Obj
 */
public
function ajaxRuturn($code, $msg, $data = [])
{
    header('Content-Type:application/json; charset=utf-8');
    $array['status'] = $code;
    $array['msg'] = $msg;
    $array['data'] = $data;
    exit(json_encode($array));
}

/**
 * @author by 张超 <Email:416716328@qq.com web:http://www.zhangchao.name>
 * @name 获取当前用户所属的所有菜单
 * @version 1.0.0
 * @funName get_menus
 * @param $uid
 * @return  Obj
 */
public
function get_menus()
{
    //判断是否开启了无权限、但显示的配置
    if (Config::set("auth.IS_SHOW_AUTH")) {
        $map[] = ['ismenu', 'eq', 1];
    } else {
        //查询用户所属的用户组
        $AuthGroupAccess = new AuthGroupAccess();
        $groupResult = $AuthGroupAccess->where('uid', $this->userInfo['id'])->find();
        if (!$groupResult) $this->ajaxRuturn(400, "参数错误！");
        $AuthGroup = new AuthGroup();
        $authGroupResult = $AuthGroup->where("id", $groupResult['group_id'])->find();
        if (!$authGroupResult) $this->ajaxRuturn(400, "参数错误！");
        //拆分权限
        $rules = explode(",", $authGroupResult['rules']);
        //组装条件
        $map[] = ['id', 'in', $rules];
        $map[] = ['ismenu', 'eq', 1];
    }
    $rulesModel = new MenusRule();
    $resultRules = $rulesModel->where($map)->select()->toArray();
    if (!$resultRules) $this->ajaxRuturn(400, "暂无相关菜单！");
    return $resultRules;
}

public
function check_login()
{
    if (session(Config::get("auth.DEFAULT_LOGIN_SESSION"))) {
        return true;
    }
    if ($this->request->controller() == 'Login') {
        return true;
    }
    return false;
}
}